    package com.dkx.springbootwebsocket.listener;

    import com.dkx.springbootwebsocket.service.WebSocketMessageService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.event.EventListener;
    import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
    import org.springframework.stereotype.Component;
    import org.springframework.web.socket.messaging.SessionConnectedEvent;
    import org.springframework.web.socket.messaging.SessionDisconnectEvent;
    import org.springframework.web.socket.messaging.SessionSubscribeEvent;

    import java.security.Principal;
    import java.util.Map;

    /*
    *   WebSocket事件监听器
    * */
    @Component
    @Slf4j
    public class WebSocketEventListener {

        @Autowired
        private WebSocketMessageService messageService;

        @EventListener
        public void handleWebSocketConnectListener(SessionConnectedEvent event) {
            StompHeaderAccessor headers = StompHeaderAccessor.wrap(event.getMessage());
            String sessionId = headers.getSessionId();

            // 从session属性中获取userId
            Map<String, Object> sessionAttributes = headers.getSessionAttributes();
            String userId = null;

            if (sessionAttributes != null) {
                userId = (String) sessionAttributes.get("userId");
            }

            // 如果session属性中没有，尝试从用户主体获取
            if (userId == null) {
                Principal principal = headers.getUser();
                if (principal != null) {
                    userId = principal.getName();
                }
            }

            // 如果还没有，尝试从原生header获取
            if (userId == null) {
                userId = headers.getFirstNativeHeader("userId");
            }

            if (userId != null) {
                messageService.handleUserOnline(userId, sessionId);
                log.info("用户连接成功: userId={}, sessionId={}", userId, sessionId);

                // 不在这里发送离线消息，等待订阅建立
            } else {
                log.warn("连接事件中未找到userId, sessionId={}, headers={}", sessionId, headers.toString());
            }
        }

        // 添加订阅事件监听
        @EventListener
        public void handleSubscriptionEvent(SessionSubscribeEvent event) {
            StompHeaderAccessor headers = StompHeaderAccessor.wrap(event.getMessage());
            String destination = headers.getDestination();
            String sessionId = headers.getSessionId();

            // 从session属性中获取userId
            Map<String, Object> sessionAttributes = headers.getSessionAttributes();
            String userId = null;

            if (sessionAttributes != null) {
                userId = (String) sessionAttributes.get("userId");
            }

            // 如果session属性中没有，尝试从用户主体获取
            if (userId == null) {
                Principal principal = headers.getUser();
                if (principal != null) {
                    userId = principal.getName();
                }
            }

            if (userId != null && destination != null) {
                log.info("订阅事件: userId={}, destination={}, sessionId={}", userId, destination, sessionId);

                // 如果是个人消息队列的订阅，发送离线消息
                if (destination.contains("/user/" + userId + "/queue/messages")) {
                    log.info("个人消息订阅已建立，准备发送离线消息: userId={}", userId);
                    messageService.delayedSendOfflineMessages(userId);
                }
            }
        }

        @EventListener
        public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
            StompHeaderAccessor headers = StompHeaderAccessor.wrap(event.getMessage());
            String sessionId = headers.getSessionId();

            // 从session属性中获取userId
            Map<String, Object> sessionAttributes = headers.getSessionAttributes();
            String userId = null;

            if (sessionAttributes != null) {
                userId = (String) sessionAttributes.get("userId");
            }

            // 如果session属性中没有，尝试从用户主体获取
            if (userId == null) {
                Principal principal = headers.getUser();
                if (principal != null) {
                    userId = principal.getName();
                }
            }

            if (userId != null) {
                messageService.handleUserOffline(userId);
                log.info("用户断开连接: userId={}, sessionId={}", userId, sessionId);
            } else {
                log.warn("断开连接事件中未找到userId, sessionId={}", sessionId);
            }
        }
    }